(function() {
	"use strict";

	/**
	 * 整个是一个树
	 */
	function Tree(option) {
		this.option = option;
		this.dom = option["dom"];
		this.data = option["data"];
		this.data.sort(soryByIndex);
		this.items = {};
		initTree.call(this);
	}

	function initTree() {
		var btns = this.data;
		var len = btns.length;
		for (var i = 0; i < len; i++) {
			var data = this.data[i];
			this.addItem(data);
		}
	}

	Tree.prototype.reInit = function(data){
		this.dom.html("");
		this.data = data;
		this.data.sort(soryByIndex);
		this.items = {};
		initTree.call(this);
	}
	
	Tree.prototype.addItem = function(data) {
		if(!data){
			var ptrs = $("tr[level='0']", this.dom);
			var temIndex = 0;
			var plen = ptrs.length;
			if(plen>0){
				temIndex = plen;
			}
			data = {
					name : "",
					index : temIndex,
					type : "view",
					url : ""
			}
		}
		var item = new Item(data, false, this, null);
		item.parent = null;
		var items = data.sub_button;
		if (items) {
			items.sort(soryByIndex);
			var len = items.length;
			for (var i = 0; i < len; i++) {
				var data = items[i];
				item.addItem(data);
			}
		}
	}

	Tree.prototype.save = function(scuu, fail) {
		var jsons = [];
		var dom = this.dom;
		var ptrs = $("tr[level='0']", dom);
		ptrs.sort(function(o1, o2) {
			var val1 = getIndex(o1);
			var val2 = getIndex(o2);
			return val1 > val2;
		})
		if(ptrs.length >3){
			fail("主菜单最多只能有3个");
			return false;
		}
		for (var i = 0, len = ptrs.length; i < len; i++) {
			var ptr = ptrs[i];
			var index = getIndex(ptr);
			if (index < 0 || index > 2) {
				fail("主菜单只能有3个，序号范围是0-2");
				return false;
			} else {
				var name = getName(ptr);
				if (isNull(name)) {
					fail("主菜单名称不能唯空");
					return false;
				} else {
					var btn1 = {
							name : name,
							index : index
					};
					jsons.push(btn1);
					var obj = $(ptr).data("obj");
					var items = toArray(obj.items);
					var jlen = items.length;

					if (jlen) {
						items.sort(function(o1, o2) {
							var val1 = getIndex(o1);
							var val2 = getIndex(o2);
							return val1 > val2;
						});
						if(jlen > 5){
							fail("子菜单最多只能有5个");
							return false;
						}
						var subBtns = btn1.sub_button = [];
						for (var j = 0; j < jlen; j++) {
							var item = items[j].dom;
							var pindex = getIndex(item);
							if (pindex < 0 || pindex > 4) {
								fail("子菜单只能有5个，序号范围是0-4");
								return false;
							} else {
								var pname = getName(item);
								if (isNull(pname)) {
									fail("子菜单名称不能为空");
									return false;
								} else {
									var url = getUrl(item);
									var checkFunc = this.option.urlCheck;
									if(typeof checkFunc == "function"){
										if(!checkFunc(url)){
											fail("URL格式错误")
											return false;
										}
										
									}
									if(isNull(url)){
										fail("子菜单跳转连接不能为空");
										return false;
									}else{
										var subObj = {
												name : pname,
												type : getType(item),
												index : pindex,
												url : url
										};
										subBtns.push(subObj);
									}
										
								}
							}
						}
					}else{
						var purl = getUrl(ptr);
						var checkFunc = this.option.urlCheck;
						if(typeof checkFunc == "function"){
							if(!checkFunc(purl)){
								fail("URL格式错误")
								return false;
							}
							
						}
						btn1.url = getUrl(ptr);
						btn1.type = getType(ptr);
					}
				}
			}
		}
		scuu({"button":jsons});
		return true;
	}


	function isNull(str) {
		return "" == str || str == null;
	}

	function getIndex(tr) {
		return $(".index_val", tr).val();
	}

	function getName(tr) {
		return $(".name_val", tr).val();
	}
	
	function getType(tr){
		return $("select", tr).val();
	}
	
	function getUrl(tr){
		return $(".url_val", tr).val();
	}

	Tree.prototype.remove = function(item) {
		var parent = item.parent;
		var index = item.index;
		var dom = item.dom;
		item.dispose();
	}
	/**
	 * 每个是一个节点
	 */
	function Item(data, flag, tree, parent) {
		this.items = {};
		var level = 0;
		this.tree = tree;
		this.data = data;
		this.parent = parent;
		var index = data.index;
		initItem.call(this, flag);
		if (this.parent == null) {
			this.tree.items["" + index] = this;
		} else {
			this.parent.items["" + index] = this;
		}
	}

	function initItem(flag) {
		var self = this;
		var item = this.data;
		var disabled = ""
		if (item.sub_button && item.sub_button.length > 0) {
			disabled = "style='display:none'";
		}
		var gap = "";
		var sheet = "";
		var btn = "";
		var level = "1";
		if (flag) {
			gap = "<div style='width:28%;height:1px;display:inline-block'></div>";
			sheet = "style='width:50%;'";
		} else {
			btn = "<i class='fa fa-plus' aria-hidden='true'></i>"
			level = "0";
		}
		var html = "<tr align='center' level ='" + level + "'>"
				+ "<td><input class='item-index index_val' value='" + item.index
				+ "'/></td>" + "<td style='position:relative;'>" + gap
				+ "<input class='item-index name_val' " + sheet + "value='" + item.name
				+ "'/>" + btn + "</td>" + "<td><select " + disabled
				+ " class='item-type' value='" + item.type + "'>"
				+ "<option value='view'>跳转连接</option>"
				/*+ "<option value='2'>发送信息</option>"*/ + "</select></td>" + "<td><input "
				+ disabled + " class='item-index url_val' value='" + item.url + "'/></td>"
				+ "<td><button type='button' class='btn btn-danger'>删除</button></td>"
				+ "</tr>"
		var dom = $(html);
		dom.data("obj", self);
		var btn = $("button", dom).click(function() {
			swal({
				title : "您确定要这个菜单吗",
				text : "将会删除它包含的子菜单",
				type : "warning",
				showCancelButton : true,
				confirmButtonColor : "#DD6B55",
				confirmButtonText : "删除",
				closeOnConfirm : false
			}, function() {
				//debugger;
				self.tree.remove(self);
				swal("删除成功！", "您已经永久删除了这条信息。", "success");
			});
		});
		$("i", dom).click(function() {
			var pdom = $(self.dom);
			var lastObj = getLastDom(self.items);
			var index = lastObj == null ? -1 : lastObj.getIndex();
			self.addItem({
				index : ++index,
				name : "",
				type : "view",
				url : ""
			});
		})
		this.dom = dom;
		var parent = this.parent;
		if (parent != null) {
			var lastObj = getLastDom(parent.items);
			if (lastObj == null) {
				$(dom).insertAfter(parent.dom);
			} else {
				$(dom).insertAfter(lastObj.dom);
			}

		} else {
			$(this.tree.dom).append(dom);
		}
	}

	Item.prototype.addItem = function(data) {
		var item = new Item(data, true, this.tree, this);
		return item;
	}

	Item.prototype.remove = function(item) {
		var tree = this.tree;
		var allData = tree.data;
	}

	Item.prototype.getIndex = function() {
		return $(".index_val", this.dom).val();
	}

	Item.prototype.dispose = function() {
		$(this.dom).remove();
		this.dom = null;
		var index = this.data.index;
		if(this.parent == null){
			delete this.tree.items[index];
		}else{
			delete this.parent.items[index];
		}
		this.tree = null;
		this.data = null;
		this.parent = null;
		var items = this.items;
		if (items) {
			for ( var i in items) {
				items[i].dispose();
				delete items[i];
			}
		}
	}

	function soryByIndex(o1, o2) {
		return o1.index > o2.index;
	}

	function getLen(obj) {
		if (!obj)
			return 0;
		var m = 0;
		for ( var i in obj) {
			m++;
		}
		return m;
	}

	function toArray(obj){
		var a = [];
		for ( var i in obj) {
			a.push(obj[i]);
		}
		return a;
	}
	
	function getLastDom(obj) {
		var max = 0;
		for ( var i in obj) {
			if (max <= i) {
				max = i;
			}
		}
		return obj[max];
	}
	window.MenuTree = Tree;

})();